package aaaClicker;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;

import org.junit.*;

import static org.junit.Assert.*;
import static org.hamcrest.CoreMatchers.*;

import org.openqa.selenium.*;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxProfile;
import org.openqa.selenium.remote.RemoteWebDriver;
import org.openqa.selenium.support.ui.Select;

import com.attilax.core;
import com.attilax.collection.CollX;
import com.attilax.io.filex;
import com.attilax.io.pathx;
import com.attilax.laisens.LaisensManger;
import com.attilax.laisens.OverTimeEx;
import com.attilax.util.CstGettor;
import com.attilax.util.PropX;
import com.thoughtworks.selenium.Selenium;
import com.thoughtworks.selenium.webdriven.WebDriverBackedSelenium;
@SuppressWarnings("all")

/**
 * for chrome version
 * @author Administrator
 *
 */
public class SelemAti extends baseBrowser  {

	private boolean acceptNextAlert = true;
	private StringBuffer verificationErrors = new StringBuffer();
	static Map<String, String> PropMap = new ConcurrentHashMap();
	// private RemoteWebDriver driver;
	// public static
	static PropX px;

	/**
	 * aaaClicker.SelemAti
	 * 
	 * @param args
	 */
	public static void main(String[] args) {
		new SelemAti().main_method(args);
		// System.out.println("--f");

	}

	private   void main_method(String[] args) {
		if(args.length>0)
		{
			if(args[0].trim().equals("ff"))
				SelemAti_firefox.main(args);
			return;
		}
		browserParams.set(new HashMap());
		System.out.println(browserParams.get());
		try {
			LaisensManger
					.checkOvertime("2016-07-13", CstGettor.getDateFrmNet());
		} catch (OverTimeEx e2) {
			// TODO Auto-generated catch block
			e2.printStackTrace();
			throw new RuntimeException(e2);
		}
		// 59.58.162.141:888 111.12.251.199:80
		Map mp = new HashMap();
		
		px = new PropX(pathx.classPathParent() + "\\click.txt", "utf-8");
		px.setValue(
				PropMap,
				"start,end,showimg,proxy,title,per_invoke_sleep,per_timeout,pageload_timeout,baseUrl,ScriptTimeout");
		final List<String> li = super.getProxysLi(PropMap);
		 
		int start = Integer.parseInt(px.getProperty("start"));
		int end = Integer.parseInt(px.getProperty("end"));
		for (int i = start; i < end; i++) {
			final int j = i;
			core.execMeth_Ays(new Runnable() {

				@Override
				public void run() {
					single(li, j);

				}
			}, "--threadName" + String.valueOf(i));
			try {
				Thread.sleep(Integer.parseInt(PropMap.get("per_invoke_sleep")));
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		}
		System.out.println("--f");
		while (true) {
			try {
				Thread.sleep(5000);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	static ThreadLocal<Map> browserParams = new ThreadLocal<Map>();
	static {

	}

	// static ThreadLocal<Map> browserParams=new ThreadLocal<Map>();
	private static void single(List<String> li, int i) {
		browserParams.set(new HashMap());
		WebDriver driver = null;
		Selenium selenium;
		// PropX px = new PropX(pathx.classPathParent() +
		// "\\click.txt","utf-8");
		try {
			System.out.println("---cur start:" + String.valueOf(i));
			FirefoxProfile profile = new FirefoxProfile();
			try {
				if (PropMap.get("proxy").equals("1")) {
					// System.out.println();
					// 使用代理
					profile.setPreference("network.proxy.type", 1);
					// http协议代理配置
					String proxStr = li.get(i).trim();
					System.out.println("--use prox:" + proxStr);
					String[] prx = proxStr.split(":");
					profile.setPreference("network.proxy.http", prx[0].trim());

					profile.setPreference("network.proxy.http_port",
							Integer.parseInt(prx[1].trim()));

					browserParams.get()
							.put("network.proxy.http", prx[0].trim());
					browserParams.get().put("network.proxy.http_port",
							prx[1].trim());
					// 对于localhost的不用代理，这里必须要配置，否则无法和webdriver通讯
					profile.setPreference("network.proxy.no_proxies_on",
							"localhost");

				}else
				{
					System.out.println("---not use proxy.. in single method");
				}

			//	Proxy proxy = new Proxy(); // jeig proxy only for ie
			} catch (Exception e) {
				e.printStackTrace();
			}
			System.out.println(" show img is :" + PropMap.get("showimg"));
			if (PropMap.get("showimg").equals("0")) {

				profile.setPreference("permissions.default.image", 2);// no img
				browserParams.get().put("permissions.default.image", 2);
			}
			// System.setProperty("webdriver.firefox.bin",
			// pathx.classPathParent()+"\\Mozilla Firefox\\firefox.exe");

			driver = getChromeDriver(profile);
			// driver = new FirefoxDriver(profile);
			// String proxyStr=li.get(i);
			// proxy.setHttpProxy(proxyStr);
			// profile.set
			// seleniu

			// 第三种全部删除
			// driver.manage().deleteAllCookies();
			// driver.d
			// WebDriver driver;
			String baseUrl;
			// driver = new FirefoxDriver();
			baseUrl = "http://www.baidu.com/baidu?wd=ip+%B5%D8%D6%B7&tn=monline_4_dg";
			baseUrl = PropMap.get("baseUrl").trim();
			// baseUrl="http://atidestoon.com/getcookie.php";
			// selenium = new WebDriverBackedSelenium(driver, baseUrl);
			// selenium.deleteAllVisibleCookies();
			System.out.println("  will open url:" + baseUrl + " idx:"
					+ String.valueOf(i));
			System.out.println("--cfg:"+core.toJsonStrO88(PropMap));
			driver.manage()
					.timeouts()
					.implicitlyWait(
							Integer.parseInt(PropMap.get("per_timeout")),
							TimeUnit.SECONDS);
			System.out.println("--pageload_timeout:"+PropMap.get("pageload_timeout"));
			driver.manage()
					.timeouts()
					.pageLoadTimeout(
							Integer.parseInt(PropMap.get("pageload_timeout")),
							TimeUnit.SECONDS);
			try {
				driver.manage()
				.timeouts().setScriptTimeout(Integer.parseInt(PropMap.get("ScriptTimeout")), TimeUnit.SECONDS);
			} catch (Exception e) {
				// TODO: handle exception
			}
			System.out.println("implicitlyWaitt" + String.valueOf(i));
		 try {
				driver.get(baseUrl + "");
		} catch (TimeoutException e) {
			System.out.println("----driver.get TimeoutException:"+ e.getMessage());
		}
			System.out.println(" get(baseUrl " + String.valueOf(i));
			// 定位到所有<input>标签的元素，然后输出他们的id
			System.out.println("scan a start" + String.valueOf(i));
			// String string = "百搭欧简约时尚单肩大包手提包包";

			String tits = PropMap.get("title");
			String[] tit_a = tits.split(",");
			for (String string : tit_a) {

				try {
					System.out.println("--start click url:" + string);
					driver.findElement(By.linkText(string.trim())).click();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}

			//
			// List<WebElement> element = driver.findElements(By.tagName("a"));

			// for (WebElement e : element) {
			// System.out.println(e.toString());
			// if (e.getAttribute("href").startsWith(
			// "http://out.zhe800.com/guang/p/deal/100040878")) {
			// System.out.println(e.getAttribute("href"));
			// e.click();
			//
			// break;
			// }
			//
			// }
			System.out.println("scan a end" + String.valueOf(i));
			// String js = filex
			// .read(pathx.classPath(ClickX.class) + "\\login.js");
			// ((JavascriptExecutor) driver).executeScript(js);
			// 第三种全部删除
			// driver.manage().deleteAllCookies();
			int click_aft = 20;
			try {
				click_aft = Integer.parseInt(px.getProperty("click_aft_sleep"));
			} catch (Exception e) {
				e.printStackTrace();
			}
			try {

				Thread.sleep(click_aft * 1000);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (driver != null)
				driver.quit();
			System.out.println("---cur finish:" + String.valueOf(i));
		}

	}

	private static WebDriver getChromeDriver(FirefoxProfile profile) {
		// 在java程序中添加
		System.setProperty("webdriver.chrome.driver", pathx.classPathParent()+ "\\chromedriver.exe");
		ChromeOptions co = new ChromeOptions();

		String max = "--start-maximized";

		String proxyParem = "";
		try {
			if (browserParams.get().get("network.proxy.http") != null) {
				String proxy = browserParams.get().get("network.proxy.http")
						+ ":"
						+ browserParams.get().get("network.proxy.http_port");

				proxyParem = "-proxy-server=" + proxy;
			}else
			{
				System.out.println("---not use proxy..");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		String noimg = "";
		if (browserParams.get().get("permissions.default.image") != null
				&& browserParams.get().get("permissions.default.image")
						.equals("2"))
			noimg = "--disable-images";
		//--disable-image-transport-surface
		// haox bsin .only gui setting/privert//img
if(proxyParem.trim().length()>0)
		co.addArguments(proxyParem);
		String path = pathx.classPathParent()
				+ "\\Chrome\\Application\\chrome.exe";
		if (new File(path).exists()) {
			System.out.println(path);
			co.setBinary(path);

		}

		return new ChromeDriver(co);

	}

	@Before
	public void setUp() throws Exception {

	}

	@Test
	public void testSelemAti() throws Exception {

		// driver.findElement(By.id("kw")).click();
		// driver.findElement(By.id("kw")).clear();
		// driver.findElement(By.id("kw")).sendKeys("attilax");
		// driver.findElement(By.id("su")).click();
	}

	// @ After
	public void tearDown() throws Exception {
		// driver.quit();
		String verificationErrorString = verificationErrors.toString();
		if (!"".equals(verificationErrorString)) {
			fail(verificationErrorString);
		}
	}

	private boolean isElementPresent(By by) {
		try {
			// driver.findElement(by);
			return true;
		} catch (NoSuchElementException e) {
			return false;
		}
	}

	private boolean isAlertPresent() {
		try {
			// driver.switchTo().alert();
			return true;
		} catch (NoAlertPresentException e) {
			return false;
		}
	}

	private String closeAlertAndGetItsText() {
		return null;
		// try {
		// Alert alert = driver.switchTo().alert();
		// String alertText = alert.getText();
		// if (acceptNextAlert) {
		// alert.accept();
		// } else {
		// alert.dismiss();
		// }
		// return alertText;
		// } finally {
		// acceptNextAlert = true;
		// }
	}
}
